import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/task/create/type/task_create_choose_type_vm.dart';
import 'package:sjx/repository/model/config_model.dart';
import 'package:sjx/route/route_utils.dart';
import 'package:sjx/route/routes.dart';

// 选择任务类型页面
class TaskCreateChooseTypePage extends StatefulWidget {
  final String? taskCategoryStr;
  final bool? refreshHandle;

  const TaskCreateChooseTypePage({
    super.key,
    this.taskCategoryStr,
    this.refreshHandle,
  });

  @override
  _TaskCreateChooseTypePageState createState() => _TaskCreateChooseTypePageState();
}

class _TaskCreateChooseTypePageState extends State<TaskCreateChooseTypePage> {
  late final TaskCreateChooseTypeViewModel _viewModel;
  String? _selectedCategory;

  @override
  void initState() {
    super.initState();
    _viewModel = TaskCreateChooseTypeViewModel();
    _viewModel.requestConfiguration();
    _selectedCategory = widget.taskCategoryStr;
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _viewModel,
      child: Consumer<TaskCreateChooseTypeViewModel>(
        builder: (context, viewModel, child) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('选择任务类型'),
              leading: IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
            body: _buildBody(viewModel),
          );
        },
      ),
    );
  }

  Widget _buildBody(TaskCreateChooseTypeViewModel viewModel) {
    if (viewModel.configModel == null) {
      return const Center(child: CircularProgressIndicator());
    }

    if (viewModel.configModel!.categories.isEmpty) {
      return const Center(child: Text('暂无任务分类'));
    }

    return Column(
      children: [
        // 头部提示
        _buildHeader(),
        // 分类网格
        Expanded(
          child: _buildCategoryGrid(viewModel.configModel!.categories),
        ),
      ],
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      width: double.infinity,
      child: const Text(
        '请正确选择以下分类，否则会被拒审',
        style: TextStyle(
          fontSize: 14,
          color: Colors.grey,
        ),
      ),
    );
  }

  Widget _buildCategoryGrid(List<Category> categories) {
    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3, // 每行3个
        mainAxisSpacing: 12, // 垂直间距
        crossAxisSpacing: 12, // 水平间距
        childAspectRatio: 2.5, // 宽高比
      ),
      itemCount: categories.length,
      itemBuilder: (context, index) {
        final category = categories[index];
        final isSelected = _selectedCategory == category.categoryName;

        return _buildCategoryItem(category, isSelected);
      },
    );
  }

  Widget _buildCategoryItem(Category category, bool isSelected) {
    return GestureDetector(
      onTap: () => _handleCategorySelect(category),
      child: Container(
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFFFFECF1) : const Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(8),
          border: isSelected
              ? Border.all(color: Theme.of(context).primaryColor, width: 1)
              : null,
        ),
        child: Center(
          child: Text(
            category.categoryDescription.isNotEmpty
                ? category.categoryDescription
                : category.categoryName,
            style: TextStyle(
              fontSize: 14,
              color: isSelected ? Theme.of(context).primaryColor : Colors.black,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            ),
            textAlign: TextAlign.center,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    );
  }

  void _handleCategorySelect(Category category) {
    setState(() {
      _selectedCategory = category.categoryName;
    });

    // 如果有回调函数，执行回调并返回
    if (widget.refreshHandle != null) {
      Navigator.of(context).pop(category.categoryName);
    } else {
      // 否则跳转到任务填写页面
      _goToTaskFillInPage(category);
    }
  }

  void _goToTaskFillInPage(Category category) {
    // 跳转到任务填写页面
    RouteUtils.pushForNamed(context, RoutePath.task_create_fill_in, arguments: {'taskCategoryStr': category.categoryName,'againCreate': false, 'serviceFeePercent': category.serviceFeePercent});
  }
}